/**
 * 
 */
package ch.baeni.jee.web;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import ch.baeni.jee.data.UserRepository;
import ch.baeni.jee.model.User;
import ch.baeni.jee.util.SLL_Globals;

/**
 * ManagedBean fuer das Login
 * 
 * @author Benjamin
 * 
 */
@SessionScoped
@ManagedBean
public class LoginBean {
	private User user;
	private String username;
	private String password;

	@Inject
	UserRepository userRepo;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = SLL_Globals.getHashCode(password);
	}

	public boolean isLoggedIn() {
		return user != null;
	}

	public User getCurrentUser() {
		return user;
	}

	/**
	 * Fuehre Login aus
	 * 
	 * @return <code>String</code> fuer Navigation
	 */
	public String doLogin() {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		try {
			request.login(this.username, this.getPassword());
			user = userRepo.findUserByUsername(this.username);
			if (!user.isActive()) {
				doLogout();
			}
		} catch (ServletException e) {
			context.addMessage(null, new FacesMessage("Login failed!"));
			return "loginError";
		}
		return "links";
	}

	/**
	 * Fuehre Logout aus
	 * 
	 * @return <code>String</code> fuer Navigation
	 */
	public String doLogout() {
		FacesContext context = FacesContext.getCurrentInstance();
		if (!user.isActive()) {
			context.addMessage(null, new FacesMessage("Benutzer inaktiv!"));
		}
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		try {
			request.logout();
			user = null;
		} catch (ServletException e) {
			context.addMessage(null, new FacesMessage("Logout failed!"));
		}
		return "login";
	}
}
